package com.imageim.yimirror.common.ui.btn;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.Shader;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

import com.imageim.yimirror.R;
import com.imageim.yimirror.common.util.UIUtils;

/**
 * Created by Yuaihen.
 * on 2018/9/17
 * 圆角Button SwitchButton
 */
public class BtnCorner extends SurfaceView {

    private Paint mPaint;
    //背景颜色
    private int backgroundColor;
    private float mRx;
    private float mRy;
    private int mWidthSize;
    private int mHeightSize;
    private static final int STATE_UNSELECTED = 0;
    private static final int STATE_SELECTED = 1;
    private int state;
    //边框宽度
    private static float strokeWidth = 2;
    //圆角角度
    private static float cornerRadius = 100;
    float[] radii_left = new float[]{cornerRadius, cornerRadius, 0, 0, 0, 0, cornerRadius, cornerRadius};
    float[] radii_right = new float[]{0, 0, cornerRadius, cornerRadius, cornerRadius, cornerRadius, 0, 0};
    private Path mPath;
    private boolean isDraw;
    private boolean touchable = true;
    private String leftText = "色彩报告";
    private String rightText = "廓形报告";
    private boolean isLeft;
    private static float textSize = 30;
    private SurfaceHolder holder;
    private Canvas mCanvas;
    private LinearGradient mBackGradient;
    private int startColor = Color.parseColor("#bfc342f5");
    private int endColor = Color.parseColor("#bf49b5f8");

    public BtnCorner(Context context) {
        this(context, null);
        init(context, null);
    }

    public BtnCorner(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
        init(context, attrs);
    }


    public BtnCorner(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }


    public void setLeftText(String leftText) {
        this.leftText = leftText;
    }

    public void setRightText(String rightText) {
        this.rightText = rightText;
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BtnCornerView);
        int indexCount = typedArray.getIndexCount();
        for (int i = 0; i < indexCount; i++) {
            int attr = typedArray.getIndex(i);
            switch (attr) {
                case R.styleable.BtnCornerView_selectBgColor:
                    backgroundColor = typedArray.getColor(R.styleable.BtnCornerView_selectBgColor, 0xffff0000);
                    break;
                case R.styleable.BtnCornerView_strokeWidth:
                    strokeWidth = typedArray.getFloat(R.styleable.BtnCornerView_strokeWidth, 2);
                    break;
                case R.styleable.BtnCornerView_selectState:
                    state = typedArray.getInt(R.styleable.BtnCornerView_selectState, 0);
                    break;
                case R.styleable.BtnCornerView_isLeft:
                    isLeft = typedArray.getBoolean(R.styleable.BtnCornerView_isLeft, false);
                    break;
                case R.styleable.BtnCornerView_cornerRadius:
                    cornerRadius = typedArray.getFloat(R.styleable.BtnCornerView_cornerRadius, 50);
                    break;
                default:

            }
        }
        typedArray.recycle();

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPath = new Path();
        mPaint.setColor(Color.WHITE);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(strokeWidth);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (!touchable) {
                            return true;
                        }

                        if (selectListener != null) {
                            selectListener.onSelect(BtnCorner.this, getState());
                        }
                        break;
                    default:
                }
                return true;
            }
        });

        //        setZOrderOnTop(true);
        //解决setZOrderOnTop遮挡问题
        //                setZOrderMediaOverlay(true);
        holder = getHolder();
        holder.setFormat(PixelFormat.TRANSLUCENT);


        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder surfaceHolder) {
                if (!isDraw) {
                    isDraw = true;
                    new Thread(new MyRunnale()).start();
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
                isDraw = false;
            }
        });
    }

    private OnSelectListener selectListener;


    private class MyRunnale implements Runnable {

        @Override
        public void run() {
            while (isDraw) {
                drawView();
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public interface OnSelectListener {
        void onSelect(BtnCorner btn, boolean isSelected);
    }

    public void setSelectListener(OnSelectListener selectListener) {
        this.selectListener = selectListener;
    }

    public void setTouchable(boolean touchable) {
        this.touchable = touchable;
    }

    //        @Override
    //        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    //            int redPacketWidth = MeasureSpec.getSize(widthMeasureSpec);
    //            int redPacketHeight = MeasureSpec.getSize(heightMeasureSpec);
    //            int widthSpec = MeasureSpec.makeMeasureSpec(redPacketWidth, MeasureSpec.EXACTLY);
    //            int heightSpec = MeasureSpec.makeMeasureSpec(redPacketHeight, MeasureSpec.EXACTLY);
    //            mRx = mWidthSize / 2;
    //            mRy = mHeightSize / 2;
    //            setMeasuredDimension(widthSpec, heightSpec);
    //        }

    private boolean isInit = false;

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (!isInit) {
            mWidthSize = getMeasuredWidth();
            mHeightSize = getMeasuredHeight();
            mRx = mWidthSize / 2;
            mRy = mHeightSize / 2;
            leftNum = mWidthSize;
        }

        isInit = true;
    }


    //内部绘制圆角矩阵的宽  变量
    private float rightNum = 0;
    private float leftNum = 0;

    public void drawView() {
        mCanvas = holder.lockCanvas();
        if (mCanvas == null) {
            return;
        }

        mCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
        if (state == STATE_UNSELECTED) {
            //圆角白色矩形
            mPath.reset();
            mPaint.reset();
            mPaint.setStrokeWidth(1);
            mPaint.setAntiAlias(true);
//            mCanvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
            mPaint.setColor(Color.WHITE);
            mPaint.setStyle(Paint.Style.STROKE);
            if (isLeft) {
                mPath.addRoundRect(0, 0, mWidthSize, mHeightSize, radii_left, Path.Direction.CCW);
            } else {
                mPath.addRoundRect(0, 0, mWidthSize, mHeightSize, radii_right, Path.Direction.CCW);

            }
            mCanvas.drawPath(mPath, mPaint);

        } else {
            //圆角红色矩形
            mPath.reset();
            mPaint.reset();
            //            mPaint.setColor(backgroundColor);
            mPaint.setAntiAlias(true);
            mPaint.setStyle(Paint.Style.FILL);
            if (isLeft) {
                mBackGradient = new LinearGradient(0, 0, rightNum, mHeightSize, new int[]{startColor, endColor}, null, Shader.TileMode.CLAMP);
                mPaint.setShader(mBackGradient);
                mPath.addRoundRect(0, 0, rightNum, mHeightSize, radii_left, Path.Direction.CCW);
            } else {
                //右边  从右往左绘制
                mBackGradient = new LinearGradient(leftNum, 0, mWidthSize, mHeightSize, new int[]{endColor, startColor}, null, Shader.TileMode.CLAMP);
                mPath.addRoundRect(leftNum, 0, mWidthSize, mHeightSize, radii_right, Path.Direction.CCW);
            }
            mPaint.setShader(mBackGradient);
            mCanvas.drawPath(mPath, mPaint);
            drawDirection(isLeft);
        }

        drawText();
        if (holder != null) {
            //说明当前帧的时候，该控件已经销毁了
            try {
                holder.unlockCanvasAndPost(mCanvas);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * 从左往右或者从右往左绘制
     */
    private void drawDirection(boolean isLeft) {
        if (isLeft) {
            if (rightNum >= mWidthSize) {
                leftFinish = true;
                rightNum = mWidthSize;
            } else {
                if (!leftFinish) {
                    rightNum += 20;
                }
            }
        } else {
            if (leftNum <= 0) {
                rightFinish = true;
                leftNum = 0;
            } else {
                if (!rightFinish) {
                    leftNum -= 20;
                }
            }
        }
    }

    private boolean rightFinish = false;
    private boolean leftFinish = false;

    private void drawText() {
        mPaint.reset();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        mPaint.setTextSize(textSize);
        mPaint.setColor(Color.WHITE);
        if (isLeft) {
            mCanvas.drawText(leftText, mWidthSize / 2 - UIUtils.getTextWidth(leftText, mPaint) / 2, mHeightSize / 2
                    + UIUtils.getTextHeight(leftText, mPaint) / 2, mPaint);
        } else {
            mCanvas.drawText(rightText, mWidthSize / 2 - UIUtils.getTextWidth(rightText, mPaint) / 2, mHeightSize / 2
                    + UIUtils.getTextHeight(rightText, mPaint) / 2, mPaint);
        }
    }

    public boolean getState() {
        return state != STATE_UNSELECTED;
    }

    public void setState(int state) {
        if (this.state != state) {
            this.state = state;
        }

        leftFinish = false;
        rightFinish = false;

        if (isLeft) {
            rightNum = 0;
        } else {
            leftNum = mWidthSize;
        }

        //        isDraw = true;
    }

    public void setBtnSelected(boolean selected) {
        if (touchable) {
            if (selected) {
                setState(STATE_SELECTED);
            } else {
                setState(STATE_UNSELECTED);
            }
        }
    }


    public boolean isLeft() {
        return isLeft;
    }

    public void setLeft(boolean left) {
        isLeft = left;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        isDraw = false;
    }

}
